package cn.echisan.homework.controller;

import cn.echisan.homework.enums.Role;
import cn.echisan.homework.model.User;
import cn.echisan.homework.service.UserService;
import cn.echisan.homework.validator.RegisterCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by echisan on 2018/5/29
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String renderRegister(){
        return "register";
    }

    @PostMapping
    public String register(@Validated(RegisterCheck.class) User user, BindingResult bindingResult, Model model) {

        if (bindingResult.hasErrors()) {
            List<String> errors = new ArrayList<>();
            bindingResult.getAllErrors().forEach(objectError -> errors.add(objectError.getDefaultMessage()));
            model.addAttribute("errors", errors);
            return "register";
        }

        user.setRole(Role.ROLE_STUDENT.name());
        if (userService.insertUser(user) != 0){
            model.addAttribute("msg","注册成功");
            return "index";
        }
        model.addAttribute("msg","注册失败");
        return "register";
    }
}
